import axios, { AxiosInstance, AxiosRequestConfig, AxiosError,AxiosResponse } from "axios";

// 定义公共返回值的属性接口
interface BaseResult<R> {
  code: number;
  data: R;
}
class HttpServic {
  private http: AxiosInstance;
  constructor() {
    this.http = axios.create({
      baseURL: "http://127.0.0.1:5000",
      timeout: 3000,
    });
  }

  private addInterceptors() {
    // 添加请求拦截器
    axios.interceptors.request.use(
      function (config:AxiosRequestConfig) {
        // 在发送请求之前做些什么
        return config;
      },
      function (error:AxiosError) {
        // 对请求错误做些什么
        return Promise.reject(error);
      }
    );

    // 添加响应拦截器
    axios.interceptors.response.use(
      function (response:AxiosResponse) {
        // 2xx 范围内的状态码都会触发该函数。
        // 对响应数据做点什么
        return response;
      },
      function (error:AxiosError) {
        // 超出 2xx 范围的状态码都会触发该函数。
        // 对响应错误做点什么
        return Promise.reject(error);
      }
    );
  }

  private request<T,R>(url:string,method:string,data?:T):Promise<BaseResult<R>>{
    return new Promise((resolve,reject)=>{
        this.http({
            url,
            method,
            data:method=='put' || method=='post'?data:"",
            params:method=='get' || method=='delete'?data:"",
        }).then((res:AxiosResponse)=>{
            resolve(res.data)
        },(err:AxiosError)=>{
            reject(err)
        })
    })
  }

  public get<T,R>(url:string,data?:T){
    return this.request<T,R>(url,"get",data)
  }
  public delete<T,R>(url:string,data?:T){
    return this.request<T,R>(url,"delete",data)
  }
  public post<T,R>(url:string,data?:T){
    return this.request<T,R>(url,"post",data)
  }
  public put<T,R>(url:string,data?:T){
    return this.request<T,R>(url,"put",data)
  }
}

const http=new HttpServic();
export default http;